package manager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import model.Order;
import util.FileUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单管理类，支持订单增删改查，持久化存储到JSON文件
 */
public class OrderManager {

    private static final String ORDER_FILE = "data/orders.json";
    private List<Order> orderList;
    private Gson gson;

    public OrderManager() {
        gson = new Gson();
        loadOrders();
    }

    private void loadOrders() {
        String json = FileUtil.readFile(ORDER_FILE);
        if (json.isEmpty()) {
            orderList = new ArrayList<>();
            saveOrders();
        } else {
            Type type = new TypeToken<List<Order>>(){}.getType();
            orderList = gson.fromJson(json, type);
            if (orderList == null) orderList = new ArrayList<>();
        }
    }

    private void saveOrders() {
        String json = gson.toJson(orderList);
        FileUtil.writeFile(ORDER_FILE, json);
    }

    /**
     * 获取所有订单
     */
    public List<Order> getAllOrders() {
        return orderList;
    }

    /**
     * 根据订单ID获取订单
     */
    public Order getOrderById(int id) {
        for (Order o : orderList) {
            if (o.getId() == id) return o;
        }
        return null;
    }

    /**
     * 添加新订单，ID自动递增
     */
    public void addOrder(Order order) {
        int newId = 1;
        if (!orderList.isEmpty()) {
            newId = orderList.get(orderList.size()-1).getId() + 1;
        }
        order.setId(newId);
        orderList.add(order);
        saveOrders();
    }

    /**
     * 更新订单状态
     */
    public boolean updateOrderStatus(int id, String newStatus) {
        for (Order o : orderList) {
            if (o.getId() == id) {
                o.setStatus(newStatus);
                saveOrders();
                return true;
            }
        }
        return false;
    }

    /**
     * 删除订单
     */
    public boolean deleteOrder(int id) {
        for (Order o : orderList) {
            if (o.getId() == id) {
                orderList.remove(o);
                saveOrders();
                return true;
            }
        }
        return false;
    }
}
